package com.gui.spring.aop.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;

import java.util.Arrays;

public class CglibProxyDemo1 {

    /**
     * methodProxy 可以避免反射调用目标方法
     */

    public static void main(String[] args) {
        TargetService targetService = (TargetService)Enhancer.create(TargetService.class, (MethodInterceptor) (o, method, objects, methodProxy) -> {
            System.out.println("前置增强，打印入参：" + Arrays.toString(objects));
            // 用反射实现
            // Object result = method.invoke(new TargetService(), objects);

            // 没有用反射
            Object result = methodProxy.invoke(new TargetService(), objects);
            System.out.println("后置增强，打印返回值：" + result);
            return result;

        });
        targetService.foo(1);
        System.out.println(targetService.getClass());
    }



    static class TargetService {

        // CGLIB 的实现原理是通过继承父类，重写父类方法来实现，所以父类的方法不能是 final 的
        public String foo(Integer type) {
            System.out.println("foo..." + type);
            return "success";
        }
    }
}
